<template>
  <div
    @mousedown="onMousedown($event)"
    @mousemove="onMousemove($event)"
    @mouseup="onMouseup"
  >
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "moveContainer",
  data() {
    return {
      x: 0,
      y: 0,
      dx: 0,
      dy: 0,
      isMousedown: false,
      isMousemove: false,
      isForwards: false,
      target: null,
      forwards: false,
      data: null,
    };
  },
  methods: {
    onMousedown(e) {
      // firefox 没有e.path这个属性
      if (!e.path) {
        const path = []
        let eleCursor = e.target
        while (eleCursor !== e.currentTarget) {
          path.push(eleCursor)
          eleCursor = eleCursor.parentElement
        }
        e.path = path
      }
      for (let ele of e.path) {
        if (ele === document) {
            break;
        }
        const isMove = /ty-move-item/.test(ele.className);
        const forwards = ele.getAttribute("ty-move-forwards");
        if (isMove) {
          this.data = ele.ty_move_data;
          this.forwards = forwards === 'true'? true : false;
          this.target = ele;
          break;
        }
      }
      if (!this.target) {
        return;
      }
      this.$emit("mouse-down", e);
      this.isMousedown = true;
      this.dx = e.pageX;
      this.dy = e.pageY;
      const transformMatrix = getComputedStyle(this.target).transform.split(
        ","
      );
      this.x = parseInt(transformMatrix[transformMatrix.length - 2], 0);
      this.y = parseInt(transformMatrix[transformMatrix.length - 1], 0);
      // 初次移动时，元素上并没有transform，所以getComputedStyle(this.target).transform获取的是['none']
      // 如果没有设置forwards在mouseup中会清除transform
      if (Number.isNaN(this.x)) {
        this.x = 0;
        this.y = 0;
      }
    },
    onMousemove(e) {
      if (!this.isMousedown) {
        return;
      }
      this.isMousemove = true;
      this.$emit("mouse-move", e, this.data);
      this.target.style.transform = `translate(${
        this.x + e.pageX - this.dx
      }px,${this.y + e.pageY - this.dy}px)`;
    },
    onMouseup() {
      this.isMousedown = false;
      // 没有点到item上，就触发cancel
      if (!this.target) {
        this.$emit("mouse-cancel");
        this.$emit("mouse-up", this.data);
        return;
      }
      this.$emit("mouse-up", this.data);
      if (!this.isMousemove) {
          this.$emit('click', this.data);
      }
      if (!this.forwards) {
          this.target.style.transform = '';
      }
      this.isMousemove = false;
      this.data = null;
      this.forwards = false;
      this.target = null;
    },
  },
};
</script>

<style>
</style>